//
//  ViewController.m
//  Net2
//
//  Created by Justsoso on 16/3/28.
//  Copyright © 2016年 Justsoso. All rights reserved.
//

#import "ViewController.h"
#import <TBXML.h>
#import "NetManager.h"

#import <SVProgressHUD.h>

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (IBAction)btnX1Pressed:(id)sender
{
    BOOL logined = [NetManager longWithUserName:self.usernameTextField.text andPassWord:self.passwordTextField.text];
    if (logined)
    {
        [SVProgressHUD showInfoWithStatus:@"登录成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [self performSegueWithIdentifier:@"gotoMain" sender:nil];
        });
    }
    else
    {
        NSString *message = @"登录失败";
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
}






- (IBAction)btnX2Pressed:(id)sender
{
    
    [SVProgressHUD showWithStatus:@"正在登录"];
    
    [NetManager longWithUserName:self.usernameTextField.text andPassWord:self.passwordTextField.text successBlock:^{
        [SVProgressHUD showInfoWithStatus:@"登录成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [self performSegueWithIdentifier:@"gotoMain" sender:nil];
        });
    } failedBlock:^(NSError *error){
        [SVProgressHUD dismiss];
        NSString *message = [NSString stringWithFormat:@"错误信息:%@",[error localizedDescription]];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }];
}
- (IBAction)btnPressed:(id)sender
{
    NSString *str = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@&method=get&type=JSON",self.usernameTextField.text,self.passwordTextField.text];
    NSURL *url = [NSURL URLWithString:str];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil)
        {
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",result);
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if (dict[@"error"] != nil)
            {
                NSString *message = [NSString stringWithFormat:@"错误信息:%@",dict[@"error"]];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }
            else
            {
                [self performSegueWithIdentifier:@"gotoMain" sender:nil];
            }
        }
        else
        {
            NSLog(@"%@%@",connectionError,[connectionError localizedDescription]);
        }
    }];
}
- (IBAction)btn2Pressed:(id)sender
{
    NSString *str = @"http://localhost:8080/MJServer/login";
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@&type=JSON",self.usernameTextField.text,self.passwordTextField.text];
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    urlRequest.HTTPMethod = @"POST";
    urlRequest.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    [SVProgressHUD showWithStatus:@"正在登录"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil)
        {
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",result);
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if (dict[@"error"] != nil)
            {
                [SVProgressHUD dismiss];
                NSString *message = [NSString stringWithFormat:@"错误信息:%@",dict[@"error"]];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }
            else
            {
                [SVProgressHUD showInfoWithStatus:@"登录成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    [self performSegueWithIdentifier:@"gotoMain" sender:nil];
                });
                
            }
        }
        else
        {
            NSLog(@"%@%@",connectionError,[connectionError localizedDescription]);
        }
    }];

}

- (IBAction)btn3Pressed:(id)sender
{
    NSString *str = @"http://localhost:8080/MJServer/login";
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@&type=XML",self.usernameTextField.text,self.passwordTextField.text];
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    urlRequest.HTTPMethod = @"POST";
    urlRequest.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    [SVProgressHUD showWithStatus:@"正在登录"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil)
        {
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",result);
            TBXML *xml = [[TBXML alloc] initWithXMLData:data error:nil];
            TBXMLElement *root = xml.rootXMLElement;
            NSString *elementName = [TBXML elementName:root];
            NSString *info = [TBXML textForElement:root];
            
            if ([elementName isEqualToString:@"error"])
            {
                [SVProgressHUD dismiss];
                NSString *message = [NSString stringWithFormat:@"错误信息:%@",info];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }
            else
            {
                [SVProgressHUD showInfoWithStatus:@"登录成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    [self performSegueWithIdentifier:@"gotoMain" sender:nil];
                });
                
            }
        }
        else
        {
            NSLog(@"%@%@",connectionError,[connectionError localizedDescription]);
        }
    }];
}
@end
